package com.want.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.aliyun.oss.OSS;
import com.want.config.OssConfiguration;
import com.want.model.dto.Result;
import com.want.model.dto.ResultUtil;
import com.want.model.dto.UploadResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author WangZhiJian
 * @since 2021/12/14 0014
 */
@Slf4j
@RestController
public class PicUploadController {

    @Resource
    private OSS ossClient;
    @Resource
    private OssConfiguration.OssProperties ossProperties;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaCheckRole(value = "admin")
    public Mono<Result<String>> upload(@RequestPart("file") FilePart filePart) throws IOException {
        return saveAndReturnPath(filePart).map(ResultUtil::ofSuccess);
    }

    @PostMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaCheckRole(value = "admin")
    public Mono<UploadResult> uploadImg(@RequestPart("file") FilePart filePart) throws IOException {
        return saveAndReturnPath(filePart)
                .map(picPath -> UploadResult.builder().errno(0).data(Arrays.asList(UploadResult.picDTO.builder().url(picPath).build())).build());
    }

    @SneakyThrows
    private Mono<String> saveAndReturnPath(FilePart filePart){
        long time = System.currentTimeMillis();
        String ext = filePart.filename().substring(filePart.filename().lastIndexOf("."));
        String flodr = ResourceUtils.getURL("classpath:").getPath()
                + "static/uploadPic/";
        File flodrFile = new File(flodr);
        if(!flodrFile.exists()){
            flodrFile.mkdirs();
        }
        String path = ResourceUtils.getURL("classpath:").getPath()
                + "static/uploadPic/"+ time + ext;
        File file = new File(path);
        file.createNewFile();
        return filePart.transferTo(file)
                .then(Mono.defer(() -> Mono.just(file)))
                .map(uploadFile -> {
                    try (FileInputStream fileInputStream = new FileInputStream(uploadFile)){
                        ossClient.putObject(ossProperties.getBucket(),ossProperties.getBasePath()+ time + ext,fileInputStream);
                        try{
                            file.deleteOnExit();
                        }catch (Exception e){
                            log.error("删除本地文件{}异常！",file.toPath().toString(),e);
                        }
                        return "https://"+ ossProperties.getBucket()+"."+ossProperties.getEndpoint() +"/"+ ossProperties.getBasePath() + time + ext;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}
